<template>
  <div class="video-player-container">
    <video
      :id="'videoElement' + _channel"
      class="video-player"
      :class="hasVideo ? 'hasVideo' : 'noVideo'"
      autoplay
      playsinline
    ></video>
    <i v-if="isLoading" class="el-icon-loading"></i>
    <i v-if="!hasVideo" class="el-icon-error"></i>
  </div>
</template>

<script>
import httpRequest from "@/services";
export default {
  props: {
    channel: {
      type: [String, Number],
      default: "",
    },
  },
  data() {
    return {
      hasVideo: true,
      isLoading: false,
    };
  },
  watch: {
    channel: {
      handler(val) {
        if (!val) return;
        setTimeout(() => {
          this.playVideo().catch(console.error);
        }, 200);
      },
      immediate: true,
    },
  },
  computed: {
    _channel: {
      get() {
        return "Channel" + this.channel;
      },
    },
  },
  methods: {
    async playVideo() {
      const val = this._channel;
      const videoElement = (this.videoElement = document.getElementById(
        "videoElement" + val
      ));
      videoElement.muted = true; // 确保视频被静音
      // 创建一个新的 RTCPeerConnection 实例
      const peerConnection = new RTCPeerConnection({
        iceServers: [{ urls: "stun:stun.aliyun.com:3478" }],
      });
      // 处理收到的远程媒体流
      peerConnection.ontrack = (event) => {
        videoElement.srcObject = event.streams[0];
      };
      // 收集 ICE 候选者
      peerConnection.onicecandidate = (event) => {
        if (event.candidate) {
          console.log("New ICE candidate: ", event.candidate);
          // 在实际应用中，可能需要将 ICE 候选者发送到远程服务器
        }
      };
      // 创建一个初始的 offer
      const offer = await peerConnection.createOffer({
        offerToReceiveAudio: true,
        offerToReceiveVideo: true,
      });
      await peerConnection.setLocalDescription(offer);
      // 发送 POST 请求获取 SDP 应答
      const url = `https://${window.config.host}${
        window.config.port ? ":" + window.config.port : ""
      }/rtc/v1/play/`;
      try {
        this.isLoading = true;
        const data = await httpRequest({
          url: "/rtc/v1/play/",
          method: "post",
          headers: {
            "Content-Type": "application/json",
          },
          params: {
            api: url,
            streamurl: `webrtc://${window.config.host}/NebulaStream/` + val,
            clientip: null,
            sdp: offer.sdp,
            noLoading: true,
          },
          isLoading: false,
        });
        this.hasVideo = true;
        // 设置远程描述
        const answer = new RTCSessionDescription({
          type: "answer",
          sdp: data.sdp,
        });
        await peerConnection.setRemoteDescription(answer);
      } catch (e) {
        this.hasVideo = false;
      } finally {
        this.isLoading = false;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.video-player-container {
  width: 100%;
  height: 100%;
  position: relative;
  .el-icon-error,
  .el-icon-loading {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    font-size: 30px;
    color: #fff;
  }
}
.video-player {
  width: 100%;
  height: 100%;
  background: #000;
  &.noVideo {
    background: #000;
  }
}
</style>
